#! /usr/bin/env python
#coding:utf-8
# 删除日志文件
# feilong
# 说明 例子 hotfix manager


import os
import time
import sys

str_time = "2022-10-10 00:00:00"

#检查文件时间删除
def checkLog():
    files = walkFile("/home/logs")
    for filename in files :
        m_time = (os.path.getmtime(filename))
        cur_time = strToTime(str_time)
        if m_time < cur_time :
            print(filename)
            #删除指定日期前的文件
            os.remove(filename)

# 遍历文件夹
def walkFile(file):
    for root, dirs, files in os.walk(file):
        # root 表示当前正在访问的文件夹路径
        # dirs 表示该文件夹下的子目录名list
        # files 表示该文件夹下的文件list
        pfs = []
        # 遍历文件
        for f in files:
            pf = os.path.join(root, f)
            pfs.append(pf)
        # 遍历所有的文件夹
        for d in dirs:
            print(os.path.join(root, d))

        return pfs

def strToTime(str):
    # str = "2022-10-13 20:28:54"
    #转换成时间数组
    timeArray = time.strptime(str, "%Y-%m-%d %H:%M:%S")
    #转换成时间戳
    timestamp = time.mktime(timeArray)
    return timestamp

def timeToStr(m_time):
    t_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(m_time))
    str_time = str(t_time)
    print(str_time)
    return str_time

if __name__ == '__main__':
    try:
        if len(sys.argv)==2 :
            str_time = str(sys.argv[1]).strip() #服务名
            str_time = str_time + " 00:00:00"
            print("delete file before "+str_time)
            checkLog()
        else:
             print("use example:\npython dellog.py 2022-10-01")
    except Exception as e:
        print("\ndellog.py exit! \n")
        print(str(e))